<?php

require_once '../db_connect.php';
require_once '../models/category.php';

class CategoryDAO {
    private $conn;

    public function __construct() {
        $this->conn = $GLOBALS['pdo'];
        if (!$this->conn) {
            die("Ошибка подключения к базе данных.");
        }
    }

    // Добавление новой записи в таблицу Categories
    public function addCategory(Category $category) {
        $query = "INSERT INTO Categories (name) VALUES (?)";
        $stmt = $this->conn->prepare($query);
        $stmt->execute([$category->getName()]);

        return $this->conn->lastInsertId();
    }

    // Получение записи по ID
    public function getCategoryById($id) {
        $query = "SELECT * FROM Categories WHERE id = ?";
        $stmt = $this->conn->prepare($query);
        $stmt->execute([$id]);

        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($row) {
            return new Category(
                $row['id'],
                $row['name']
            );
        }

        return null;
    }

    // Обновление записи
    public function updateCategory(Category $category) {
        $query = "UPDATE Categories SET name = ? WHERE id = ?";
        $stmt = $this->conn->prepare($query);
        return $stmt->execute([
            $category->getName(),
            $category->getId()
        ]);
    }

    // Удаление записи по ID
    public function deleteCategory($id) {
        $query = "DELETE FROM Categories WHERE id = ?";
        $stmt = $this->conn->prepare($query);
        return $stmt->execute([$id]);
    }

    // Получение всех записей
    public function getAllCategories() {
        $query = "SELECT * FROM Categories";
        $stmt = $this->conn->prepare($query);
        $stmt->execute();

        $categoryList = [];
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $categoryList[] = new Category(
                $row['id'],
                $row['name']
            );
        }

        return $categoryList;
    }

    public function getAllCategoriesJson() {
        $categoryList = $this->getAllCategories();
        $categoryArray = array_map(function($category) {
            return [
                'id' => $category->getId(),
                'name' => $category->getName()
            ];
        }, $categoryList);
    
        return json_encode($categoryArray);
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['action']) && $_GET['action'] === 'getAllCategoriesJson') {
    $dao = new CategoryDAO();
    echo $dao->getAllCategoriesJson();
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'deleteMultipleCategories' && !empty($_POST['ids'])) {
    $dao = new CategoryDAO();
    $ids = explode(',', $_POST['ids']);
    $errors = [];
    $successCount = 0;

    foreach ($ids as $id) {
        $success = $dao->deleteCategory(trim($id));

        if ($success) {
            $successCount++;
        } else {
            $errors[] = ['id' => $id, 'message' => 'Не удалось удалить запись.'];
        }
    }

    if ($successCount > 0 && count($errors) === 0) {
        echo json_encode(['success' => true, 'message' => 'Все выбранные записи успешно удалены.']);
    } else {
        echo json_encode(['success' => false, 'errors' => $errors]);
    }
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['action']) && $_GET['action'] === 'getCategoryById' && isset($_GET['id'])) {
    $id = $_GET['id'];
    $dao = new CategoryDAO();
    $category = $dao->getCategoryById($id);

    if ($category) {
        echo json_encode([
            'id' => $category->getId(),
            'name' => $category->getName()
        ]);
    } else {
        echo json_encode(['error' => 'Запись не найдена']);
    }
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $dao = new CategoryDAO();
    switch ($_POST['action']) {
        case 'addCategory':
            $name = $_POST['name'];

            $category = new Category(null, $name);
            $newId = $dao->addCategory($category);

            echo json_encode(['success' => true, 'message' => 'Запись добавлена', 'newId' => $newId]);
            break;
        case 'updateCategory':
            $id = $_POST['id'];
            $name = $_POST['name'];

            $category = new Category($id, $name);
            $success = $dao->updateCategory($category);

            if ($success) {
                echo json_encode(['success' => true, 'message' => 'Запись обновлена']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Ошибка при обновлении записи']);
            }
            break;
    }
    exit();
}
?>